﻿using System;
using System.Web;
using System.Web.SessionState;
using Wedn.Core.Entity;
using Wedn.Core.Service;
using Wedn.Core.Utility;

namespace Wedn.Web.UI.Admin.Handler
{
    /// <summary>
    /// 用户登录处理
    /// </summary>
    public class Login : IHttpHandler, IRequiresSessionState
    {
        HttpContext context;
        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            context.Response.ContentType = "text/plain";
            string uid = RequestHelper.FormString("user_login");
            string pwd = RequestHelper.FormString("user_password");
            if (string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(pwd))
                CheckLogin();
            else
            {
                //2013年4月1日 18:30:55取消登录验证码, 原因:增强客户体验
                //string vCode = RequestHelper.FormString("validate_code");
                //string sessionCode = Session["ValidateCode"] == null ? string.Empty : Session["ValidateCode"].ToString();
                //Session["ValidateCode"] = null;
                //if (sessionCode == vCode)
                //{
                UserManager userManager = new UserManager();
                User currentUser = null;
                LoginResult res = userManager.Login(uid, pwd, out currentUser);
                switch (res)
                {
                    case LoginResult.Success:
                        if (context.Session["CurrentUser"] == null)
                            context.Session["CurrentUser"] = currentUser;
                        if (RequestHelper.FormString("ck_remember_me") == "true")
                        {
                            string cValue = userManager.GetEncryptUserInfo(currentUser);
                            HttpCookie cookie = new HttpCookie(Config.SitePrefix + "URM", cValue);
                            cookie.Expires = DateTime.Now.AddMonths(1);
                            context.Response.Cookies.Add(cookie);
                        }
                        //Response.Cookies[Config.SitePrefix+"UserInfo"].Value=
                        ResponseStr("Success");
                        break;
                    case LoginResult.PasswordError:
                        ResponseStr("PasswordError");
                        break;
                    case LoginResult.NonExistent:
                        ResponseStr("NonExistent");
                        break;
                    case LoginResult.Awaiting:
                        ResponseStr("Awaiting");
                        break;
                }
                //}
                //else
                //{
                //    ResponseStr("ValidateCodeError");
                //}
            }
        }

        /// <summary>
        /// 校验用户是否已经登录
        /// </summary>
        private void CheckLogin()
        {
            User CurrentUser = context.Session["CurrentUser"] as User;
            if (CurrentUser != null)
                ResponseStr("islogin");
            else
                CheckCookies();
        }

        /// <summary>
        /// 校验cookie登录
        /// </summary>
        private void CheckCookies()
        {
            HttpCookie cookie = context.Request.Cookies[Config.SitePrefix + "URM"];
            if (cookie != null)
            {
                UserManager userManager = new UserManager();
                User cookieUser = userManager.GetDecryptUserInfo(cookie.Value);
                if (cookieUser != null)
                {
                    User currentUser = null;
                    LoginResult res = userManager.Login(cookieUser.Login, cookieUser.Password, out currentUser, true);
                    if (res == LoginResult.Success)
                    {
                        //审核通过
                        if (context.Session["CurrentUser"] == null)
                            context.Session["CurrentUser"] = currentUser;
                        ResponseStr("islogin");
                    }
                }
                else
                {
                    //密码被修改了.清除cookie
                    context.Response.Cookies[Config.SitePrefix + "URM"].Expires = DateTime.Now.AddDays(-1);
                }
            }
        }

        private void ResponseStr(string str)
        {
            context.Response.Clear();
            context.Response.Write(str);
            //context.Response.Flush();
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}